package com.hy.utils.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(value = "/view/*",filterName = "LoginFilter")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
//|| uri.endsWith(".jsp")
        String uri = request.getRequestURI();
        if(uri.endsWith("login.jsp") || uri.endsWith(".png") || uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".json") ){
            //放行
            filterChain.doFilter(request, response);
            return;
        }else if(uri.endsWith("login")){
            String ac = request.getParameter("ac");
            if("selectLogin".equals(ac)){
                filterChain.doFilter(request, response);
                return;
            }else if("selectPhone".equals(ac)){
                filterChain.doFilter(request, response);
                return;
            }else if("insertUser".equals(ac)){
                filterChain.doFilter(request, response);
                return;
            }
        }

        HttpSession session = request.getSession(true);

        if(session != null){
            Object username = session.getAttribute("username");
            if(username == null){ //说明没有登录
                response.sendRedirect(request.getContextPath()+"/login/login.jsp");
                return;
            }
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
